﻿using System;
using System.IO;

namespace ImageProcessing.Comm
{
    public class ImageSaver
    {
        public static void SaveImageFromStream(Stream imageStream, string filePath)
        {
            // 确保Stream可以被读取
            if (!imageStream.CanRead)
            {
                throw new InvalidOperationException("Stream cannot be read.");
            }

            // 确保Stream的当前位置不是末尾
            if (imageStream.Position == imageStream.Length)
            {
                throw new InvalidOperationException("Stream is at the end. Cannot save an empty stream.");
            }

            // 将Stream的当前位置重置到开始位置
            imageStream.Seek(0, SeekOrigin.Begin);

            // 使用FileStream来写入文件
            using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                // 将Stream的内容复制到FileStream中
                imageStream.CopyTo(fileStream);
            }
        }
    }
}